package mvc.core;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.core.config.ConfigContext;
import mvc.core.log.Logger;
import mvc.core.util.Util;

/**
 * 应用程序入口
 * 
 * @author liuzy
 * @version 2015年5月15日
 */
public class LauncherFilter implements Filter {
	
	private Logger logger = Logger.getLogger(LauncherFilter.class);
	
	/**
	 * 0.加载配置,读log.properties和jdbc.properties<br>
	 * 1.读config.xml加载Bean,注入${}属性<br>
	 * 2.加载注解Bean,扫描@Bean|@Service|@Batis,注入@Inject属性<br>
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		logger.debug("服务初始化...");
		ConfigContext.loadProperties("log.properties", "jdbc.properties");
		BeanFactory.loadBeanByXml("config.xml");
		BeanFactory.loadBeanByAnnotations();
		BeanFactory.iocBean();
		logger.debug("服务初始化完成");
	}

	/**
	 * 拦截URI请求
	 */
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		request.setCharacterEncoding("UTF-8");
		String uri = request.getRequestURI();
		String type = request.getMethod();
		logger.debug("收到请求:uri=" + uri + ", type=" + type + ", params=" + Util.paramsJSON(request));
		Response re = null;
		ActionMapping actionMapping = BeanFactory.getActionMapping(uri);
		if (actionMapping != null) {
			if (!actionMapping.getType().contains(type)) {
				logger.debug("URI路径" + actionMapping.getPath() + "没有映射类型" + request.getMethod());
			} else {
				logger.debug("请求有效,开始处理:");
				try {
					Object action = BeanFactory.getBean(actionMapping.getActionClass());
					Object obj = actionMapping.getMethod().invoke(action);
					if (obj instanceof Response) {
						re = (Response) obj;
					} else if (obj instanceof File) {
						File file = (File) obj;
						re = new Response(new File(file.getFileName(), file.getFileBytes()));
					} else {
						re = new Response(obj);
					}
					logger.debug(re.toString());
					re.send(response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				logger.debug("处理完成");
			}
		} else {
			logger.debug("URI路径无映射,请求无效");
		}
	}

	@Override
	public void destroy() {
		BeanFactory.stop();
	}

}
